
package com.scalar.chiptrack.sales.actions;

import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.sales.Region;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.NewCustomerDAO;
import com.scalar.chiptrack.sales.forms.AddNewRegionForm;
import com.scalar.chiptrack.users.User;


public class AddNewRegionAction extends ChipTrackAction {

    private static final String ACTION_NAME = "/addNewRegion.do" ;  // Added by Basha (08/08/2003)

    private ArrayList allregions = new ArrayList();
    private String region = null;

    public ActionForward execute (ActionMapping mapping,
                                      ActionForm form,
                                      HttpServletRequest request,
                                      HttpServletResponse response)
                                     throws Exception {


        HttpSession session = request.getSession();


             User user = (User)session.getAttribute (SessionKeys.USER_KEY);

             if (user == null)
             {
                session.setAttribute (SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString());
                return (mapping.findForward ("login"));
             }


		HashMap errors = new HashMap();
		request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);

		HashMap info = new HashMap();
		request.setAttribute (SessionKeys.INFO_MESSAGES, info);


		AddNewRegionForm addregionform=(AddNewRegionForm) form;
		String action = request.getParameter("action");
		//int customerId = Integer.parseInt(request.getParameter("customerId"));
        int customerId = -1;
 		//System.out.println("action in region "+action +"customerId "+customerId);

		// Modified by Sarada on 3rd Feb 2004 to get all  regions of that customer id
        //request.setAttribute("regions",CustomerDAO.getAllRegionsWithActions(customerId));
        request.setAttribute("regions",CustomerDAO.getAllRegionsWithActions());
        if ("disable".equalsIgnoreCase(request.getParameter("regionstatus")) == true)
        {
          String regionToDelete = request.getParameter("region");
          int regionId = Integer.parseInt( request.getParameter("regionId") );
          //System.out.println("regionToDelete  "+regionToDelete);

          if ((regionToDelete != null) && (regionToDelete.trim().length() != 0))
          {
           try {
		   // Modified by Sarada on 3rd Feb 2004 to disable region of that customer id
                 // CustomerDAO.deleteRegion(regionToDelete , customerId);
                  CustomerDAO.deleteRegion( regionId);
                  info.put (regionToDelete + " has been disabled", null);
               }
              catch (ScalarException se)
              {
                  se.printStackTrace ();
                  errors.put ("Internal Server Error", "Could not delete \"" + regionToDelete + "\"");
              }
          }
        }

        else if ("activate".equalsIgnoreCase(request.getParameter("regionstatus")) == true)
        {
             String regionToActivate = request.getParameter("region");
          if ((regionToActivate != null) && (regionToActivate.trim().length() != 0))
          {
            try
            {
		// Modified by Sarada on 3rd Feb 2004 to enable region of that customer id
              //CustomerDAO.activateRegion (regionToActivate, customerId);
              int regionId = Integer.parseInt( request.getParameter("regionId") );
              CustomerDAO.activateRegion ( regionId );
              info.put (regionToActivate + " has been activated", null);
            }
            catch (ScalarException se)
            {
              se.printStackTrace ();
              errors.put ("Internal Server Error", "Could not activate \"" + regionToActivate + "\"");
            }
          }
        }

		if("insertRegion".equalsIgnoreCase(action))
		{
			region = addregionform.getNewRegion();
			//region = request.getParameter("newRegion");
			boolean success = false;
			boolean temp = false;


			if((region == null) || (region.trim().length() == 0)) {
				errors.put ( ERROR_CUSTOMER_INVALID_REGION, null );
				return (mapping.findForward ("success"));
			}


			//allregions = CustomerDAO.getAllRegionsWithActions(customerId);
            allregions = CustomerDAO.getAllRegionsWithActions();
			int allregionsSize = allregions.size();
			Region regions = new Region();

			for (int j=0; j<allregionsSize; j++)
			{
				regions = (Region)allregions.get(j);
				String regionname = regions.getRegion();
				if((region != null)  && (regionname != null))
				{
					if (region.trim().equalsIgnoreCase(regionname.trim()))
					{
						temp= true;
						break;
					}
				}
			}//for end

			if (temp == true) {
				errors.put ( region +" " + ERROR_REGION_ALREADY_EXISTS, null );
				return (mapping.findForward ("success"));
			}

			try {
				 // Modified by Sarada on 3rd Feb 2004 to insert region of that customer id
					//CustomerDAO.insertRegion (null, region , customerId);
                    CustomerDAO.insertRegion (null, region );
                    addregionform.reset( mapping,request );
					info.put ( INFO_REGION_SUCCESSFULLY_STORED, null );
					success = true;
			   }
			catch (ScalarException se) {
				errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
				//errors.put ("Internal Server Error", "Could not cancel packingslip (" + packingSlipForm.getLabel() + ")");
				se.printStackTrace();
			}
        }
        //Added by varma 7 jan 2005 to update the Region Name
        else if ( "editRegion".equalsIgnoreCase( action ) )
        {
			String newRegion = request.getParameter("newRegion");
            String oldRegion = request.getParameter("oldRegion");

            boolean success = false;
            boolean temp = false;

			if((newRegion == null) || (newRegion.trim().length() == 0)) {
				errors.put ( ERROR_CUSTOMER_INVALID_REGION, null );
				return (mapping.findForward ("success"));
			}
            //To check whether the region already exists in the DB
            allregions = CustomerDAO.getAllRegionNames() ;
            String existingRegion = "";
			for (int j=0; j<allregions.size() ; j++)
			{
				existingRegion = (String)allregions.get(j);

				if( (newRegion != null) && (existingRegion != null) )
				{
					if ( !newRegion.equalsIgnoreCase(oldRegion) && newRegion.trim().equalsIgnoreCase(existingRegion) )
					{
						temp= true;
						break;
					}
				}
			}//for end
            //if already exists means throw an error msg
			if (temp == true) {
				errors.put ( newRegion +" " + ERROR_CUSTOMER_REP_ALREADY_EXISTS, null );
                //addregionform.reset( mapping,request );
				return (mapping.findForward ("success"));
			}


            DBTransaction dbTransaction = null;
			try {
                dbTransaction = DBTransaction.getInstance();
                dbTransaction.begin();
                //UPdating the region into DB
                NewCustomerDAO.updateRegion ( dbTransaction, oldRegion, newRegion );
                addregionform.reset( mapping,request );
				info.put ( INFO_REGION_SUCCESSFULLY_UPDATED, null );
				success = true;
			}
			catch (ScalarException se) {
				errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
				se.printStackTrace();
			}
            finally
            {
                if( success == true)
                {
                    dbTransaction.commit();
                }
                else
                {
                    dbTransaction.rollback();
                }
            }
        }


       	 //request.setAttribute("regions",CustomerDAO.getAllRegionsWithActions(customerId));
        request.setAttribute("regions",CustomerDAO.getAllRegionsWithActions());
	 return (mapping.findForward ("success"));
    }

}
